/*
 * @Author: 曹捷
 * @Date: 2019-08-01 14:25:13
 * @LastEditors: 曹捷
 * @LastEditTime: 2021-07-30 11:14:35
 * @Description: ajax 请求
 */
import axios from 'axios'
import { userRole } from './../../utils/auth'
import { Message } from "element-ui"
import { System } from './../index'
// 创建axios实例
export default function (ajaxConfig = {}) {
    const service = axios.create({
        // baseURL: URL, // api的base_url
        timeout: 60000, // 请求超时时间
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }
    })

    // request拦截器
    service.interceptors.request.use(config => {
        // 是否要更改header内容
        if (config.isFile) {
            config.headers['Content-Type'] = 'multipart/form-data'
        }
        if (typeof config.type !== 'undefined' && config.type == 'download') {
            config['responseType'] = 'blob'
        }
        // 用户标识判断
        if (config.params) {
            config.data = {
                ...config.data,
                ...config.params
            }
        }
        if (config.method === 'post' || config.method === 'put') {
            config.headers['Content-Type'] = 'application/json'
            // 设置参数拼接方式
        }
        if (ajaxConfig.ajax.request) {
            return ajaxConfig.ajax.request(config)
        }
        let userInfo = userRole.get()
        if (userInfo) {
            let user = JSON.parse(userInfo)
            if (user && user.accessToken) {
                config.headers['Authorization'] = user.accessToken
                config.headers['UserId'] = user.userId
            }
        }
        config.headers['SystemType'] = 'manager'
        // 签名

        return config
    }, error => {
        Promise.reject(error)
    })

    // respone拦截器
    service.interceptors.response.use(
        response => {
            if (response.status === 200) {
                if (ajaxConfig.ajax && ajaxConfig.ajax.response) {
                    return ajaxConfig.ajax.response(response)
                }
                let res = response.data
                if (res.code === '0004') {
                    // token 已经过期，重新拉取新的token再重新发送之前请求
                    let config = response.config
                    var backoff = new Promise(function (resolve) {
                        let userInfo = userRole.get()
                        let user = JSON.parse(userInfo)
                        let params = {
                            userId: user.userId,
                            refleshToken: user.refleshToken
                        }
                        System.API.reflesh(params).then(res => {
                            user.accessToken = res.accessToken
                            // util.cookie.set('user', user)
                            userRole.set(user)
                            resolve()
                        })
                    })
                    return backoff.then(function () {
                        return service(config)
                    })
                } else if (res.code === '0005' || res.code === 'LOGIN.001') {
                    // 登陆超时 或者是token异常 ，跳登陆页面
                    Message.error(res.errorMsg)
                    System.ROUTER.push({
                        path: '/login'
                    })
                    // router.push({ path: '/login' })
                    Promise.reject()
                } else {
                    if (response.headers['content-type'].indexOf('octet-stream') !== -1) {
                        return response
                    } else {
                        if (response.data.code === ajaxConfig.successCode) {
                            return response.data.data
                        } else {
                            Message({
                                type: "error",
                                message: response.data.errorMsg
                            });
                            return Promise.reject()
                        }
                    }

                }
            } else {
                Message({
                    type: "error",
                    message: response.data.errorMsg
                })
                Promise.reject()
            }
        },
        error => {
            Promise.reject(error)
            return {
                code: '1',
                errorMsg: '请求异常，请稍后重试'
            }
        }
    )
    return service
}
